import React, { useEffect, useState } from "react";
import store from "./redux/store";
// 将action代码抽离出来
import { getListAction } from "./actionCreator/ListActionCreator";
export default function Home() {
    const [list, setlist] = useState(store.getState().ListReducer.list);
    useEffect(() => {
        if (store.getState().ListReducer.list.length === 0) {
            // 发送请求
            console.log("发送请求");
            store.dispatch(getListAction());
        } else {
            // 读取缓存
            console.log("读取缓存");
        }
        // 订阅
        // store.subscribe()会返回一个函数，执行该函数就会取消这次订阅
        const unsubscribe = store.subscribe(() => {
            console.log("home组件订阅");
            setlist(store.getState().ListReducer.list);
        });
        return () => {
            // 取消订阅
            // 因为该组件可以被频繁的显示（创建）和隐藏（销毁），每次创建时都会执行useEffect，导致重复订阅
            // 所以我们需要在组件销毁时取消订阅
            unsubscribe();
        };
    }, []);

    return (
        <div>
            Home页面
            <ul>
                {list.map((item) => (
                    <li key={item}>{item}</li>
                ))}
            </ul>
        </div>
    );
}
